package com.wwt.blog.imp;

import com.alibaba.fastjson.JSON;
import com.wwt.blog.pojo.SysUser;
import com.wwt.blog.service.RegisterService;
import com.wwt.blog.service.SysUserService;
import com.wwt.blog.utils.JWTUtils;
import com.wwt.blog.vo.ErrorCode;
import com.wwt.blog.vo.Result;
import com.wwt.blog.vo.param.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImp implements RegisterService {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    //加密盐
    private static final String slat="mszlu!@#";
    @Override
/*    //注册
    * 1. 判断参数 是否合法
         * 2. 判断账户是否存在，存在 返回账户已经被注册
         * 3. 不存在，注册用户
         * 4. 生成token
         * 5. 存入redis 并返回
         * 6. 注意 加上事务，一旦中间的任何过程出现问题，注册的用户 需要回滚*/

    public Result register(LoginParam loginParam) {
        String account=loginParam.getAccount();
        String password=loginParam.getPassword();
        String nickname=loginParam.getNickname();
        //判断参数是否为空
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(password)||StringUtils.isEmpty(nickname))
            return Result.result_fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        //判断账户是否存在
        SysUser user = sysUserService.getUserByAccount(account);
        if(user!=null)
            return Result.result_fail(ErrorCode.ACCOUNT_EXISTED.getCode(),ErrorCode.ACCOUNT_EXISTED.getMsg());

        //补全账号信息 先生成加密的密码
        String pwd = DigestUtils.md5Hex(password + slat);
        user=new SysUser();
        user.setAccount(account);
        user.setNickname(nickname);
        user.setPassword(pwd);
        user.setAdmin(0);
        user.setAvatar("static/img/头像1.png");
        user.setCreateDate(System.currentTimeMillis());
        user.setDeleted(0);
        user.setEmail(null);
        user.setLastLogin(System.currentTimeMillis());
        user.setMobilePhoneNumber(null);
        user.setStatus(null);
        //存入数据库
        sysUserService.insertUser(user);
        //生成token
        String token = JWTUtils.createToken(user.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.result_success(token);
    }
}
